package cn.cqsztech.mq.active.util;

import cn.hutool.core.util.ObjectUtil;

import javax.jms.*;

/**
 * ccmars
 * 2022/3/4
 **/
public class TopicSubscriber {
    public static void main(String[] args) {
        subscribeTexMessage("name");
    }

    /**
     * 消费一次
     *
     * @param topicName
     * @return
     */
    public static String subscribeTexMessageOnce(String topicName) {

        try {
            Message subscribe = ActiveMQUtil.subscribe(() -> topicName);
            if (ObjectUtil.isNotEmpty(subscribe)) {
                TextMessage message = (TextMessage) subscribe;
                return message.getText();
            }
        } catch (JMSException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 消费一次
     *
     * @param topicName
     * @return
     */
    public static void subscribeTexMessage(String topicName) {
        TopicConnection connection = ActiveMQUtil.getConnection();
        try {
            TopicSession topicSession = connection.createTopicSession(true, Session.AUTO_ACKNOWLEDGE);
            MessageConsumer consumer = topicSession.createConsumer((Topic) () -> topicName);
            while (true) {
                TextMessage receive = (TextMessage) consumer.receive();
                if (ObjectUtil.isNotEmpty(receive)) {
                    String text = receive.getText();
                    System.out.println(text);
                }
            }

        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}
